import 'package:json_annotation/json_annotation.dart';
import 'sku.dart';
import 'product.dart';
part 'cart_item.g.dart';

@JsonSerializable()
class CartItem {
  final int? id;
  final int productId;
  final int skuId;
  final String? name;
  final String? imageUrl;
  final double price;
  int quantity;
  @BoolIntConverter() // ← 这里启用转换器
  bool selected;
  final Sku? sku;
  final Product? goods;

  CartItem({
    this.id,
    required this.productId,
    required this.skuId,
    this.name,
    this.imageUrl,
    required this.price,
    required this.quantity,
    required this.selected,
    this.sku,
    this.goods,
  });

  factory CartItem.fromJson(Map<String, dynamic> json) =>
      _$CartItemFromJson(json);
  Map<String, dynamic> toJson() => _$CartItemToJson(this);
}

/// 0/1/true/false/"1"/"0" → bool 的转换器
class BoolIntConverter implements JsonConverter<bool, Object?> {
  const BoolIntConverter();
  @override
  bool fromJson(Object? json) {
    if (json is bool) return json;
    if (json is num) return json != 0;
    if (json is String) {
      final s = json.toLowerCase();
      return s == '1' || s == 'true' || s == 'yes';
    }
    return false;
  }

  /// 如果后端需要 int（0/1），保持如下；若需要 bool，返回 `v` 即可
  @override
  Object toJson(bool v) => v ? 1 : 0; // 改成 `v` 则输出 true/false
}
